package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.*;
import com.leyou.item.pojo.*;
import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shkstart
 * @create 2020-04-05 17:08
 */

@Service
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;


    public PageResult<SpuBo> querySpuPageAll(String key, Boolean saleable, Integer page, Integer rows) {
        // 分页条件
        PageHelper.startPage(page, rows);

        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 搜索条件
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }

        // 执行查询
        List<Spu> spus = this.spuMapper.selectByExample(example);

        PageInfo<Spu> pageInfo = new PageInfo<>(spus);

        List<SpuBo> spuBos = new ArrayList<>();
        spus.forEach(spu->{
            SpuBo spuBo = new SpuBo();
            // copy共同属性的值到新的对象
            BeanUtils.copyProperties(spu, spuBo);
            // 查询分类名称
            List<Category> list = categoryMapper.selectByIdList(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            List<String> collect = list.stream().map(category -> category.getName()).collect(Collectors.toList());
            String cname = StringUtils.join(collect, "/");
            spuBo.setCname(cname);
           /* List<String> names = this.categoryService.queryNamesByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            spuBo.setCname(StringUtils.join(names, "/"));*/

            // 查询品牌的名称
            spuBo.setBname(brandMapper.selectByPrimaryKey(spu.getBrandId()).getName());

            spuBos.add(spuBo);
        });

        PageResult<SpuBo> spuBoPageResult = new PageResult<>();
        spuBoPageResult.setItems(spuBos);
        spuBoPageResult.setTotal(pageInfo.getTotal());
        return spuBoPageResult;
    }

    @Transactional
    public void insertGoods(SpuBo spuBo) {
        //补全对象的参数，防止外部攻击
        spuBo.setId(null);
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        spuMapper.insert(spuBo);

        //保存spu详情
        spuBo.getSpuDetail().setSpuId(spuBo.getId());
        spuDetailMapper.insert(spuBo.getSpuDetail());

        insertSkuAndStock(spuBo);

        getAmqpSend("insert",spuBo.getId());
    }

    private void getAmqpSend(String key,Long id) {
        try {
            amqpTemplate.convertAndSend("item."+key,id);
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }


    //讲添加sku和stock做成通用方法
    @Transactional
    public void insertSkuAndStock(SpuBo spuBo){
        //保存sku数据
        List<Sku> skus = spuBo.getSkus();
        skus.forEach(s->{
            s.setId(null);
            s.setSpuId(spuBo.getId());
            s.setCreateTime(spuBo.getCreateTime());
            s.setLastUpdateTime(s.getCreateTime());
            skuMapper.insert(s);

            //保存商品对应的库存
            Stock stock = new Stock();
            stock.setSkuId(s.getId());
            stock.setStock(s.getStock());
            stockMapper.insert(stock);
        });

    }

    public SpuDetail selectSpuDetail(Long id) {
        return spuDetailMapper.selectByPrimaryKey(id);
    }
    @Transactional
    public List<Sku> selectSkuById(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> select = skuMapper.select(sku);
        select.forEach(s->{
            Stock stock = stockMapper.selectByPrimaryKey(s.getId());
            s.setStock(stock.getStock());
        });
        return select;
    }
    @Transactional
    public void updateGoods(SpuBo spuBo) {
        //对spu进行修改
        spuBo.setLastUpdateTime(new Date());
        spuMapper.updateByPrimaryKeySelective(spuBo);

        //保存spu详情
        spuBo.getSpuDetail().setSpuId(spuBo.getId());
        spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());
        //删除以前的sku
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId",spuBo.getId());
        skuMapper.deleteByExample(example);
        //删除玩以前的sku后在添加新的sku属性
        insertSkuAndStock(spuBo);

        getAmqpSend("update",spuBo.getId());
    }
    @Transactional
    public void deleteGoodsById(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        spu.setValid(false);
        spuMapper.updateByPrimaryKey(spu);

        getAmqpSend("delete",id);
    }
    @Transactional
    public void xiajiaGoodsById(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        spu.setSaleable(false);
        spuMapper.updateByPrimaryKey(spu);
    }
    @Transactional
    public void shangjiaGoodsById(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        spu.setSaleable(true);
        spuMapper.updateByPrimaryKey(spu);
    }

    public Spu getSpuById(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        return  spu;

    }

    public Brand getBrandBySpuId(Long id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
        return brand;
    }

    public Sku getSkuById(Long id) {
       return skuMapper.selectByPrimaryKey(id);
    }
}
